<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Lib_Router
 *
 * @author Zelic
 */
class Lib_Router {

    static $default_route;
    static $routes;

    static function init() {
        Lib_Router::$routes = array();
    }

    /*
     * route is an array contains 3 elements:
     * [0]module
     * [1]controller
     * [2]action
     */

    static function setDefaultRoute($route) {
        Lib_Router::$default_route = $route;
    }

    static function addRoute($URIPattern, $route) {
        Lib_Router::$routes['|' . $URIPattern . '|'] = $route;
    }

    static function cleanURI() {
        $dirtyPart = dirname($_SERVER["PHP_SELF"]) . '/';
        return substr($_SERVER["REQUEST_URI"], strlen($dirtyPart), strlen($_SERVER["REQUEST_URI"]));
    }

    static function resolve() {
        $uri = Lib_Router::cleanURI();
        if ($uri == "") {
            Lib_Router::execute(Lib_Router::$default_route);
        } else {
            if (Lib_Router::$routes == null) {
                Lib_Router::execute(Lib_Router::$default_route);
            } else {
                foreach (Lib_Router::$routes as $pattern => $route) {
                    if (preg_match($pattern, $uri, $matches)) {
                        if ($_POST!=null) {
                            $data = $_POST;
                        } else {
                            $data = array_slice($matches, 1, count($matches));
                        }
                        Lib_Router::execute($route, $data);
                        return;
                    }
                }
                Lib_Router::execute(Lib_Router::$default_route);
            }
        }
    }

    static function execute($route, $data = null) {
        $module = Lib_Util::upperCaseWord($route['module']);
        $controller = Lib_Util::upperCaseWord($route['controller']);
        $action = $route['action'];
        $controllerClass = 'App_' . $module . '_Controller_' . $controller;
        $controllerObject = new $controllerClass();
        echo $controllerObject->execute($action, $data);
    }

}
?>
